package com.wuming.house.controller;

import com.wuming.house.core.CommonResult;
import com.wuming.house.core.JsonResult;
import com.wuming.house.model.GoodImage;
import com.wuming.house.model.GoodsCate;
import com.wuming.house.service.GoodImageService;
import com.wuming.house.service.GoodsCateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xuhuai
 * @createTime 2019/8/15 16:19
 * @Description:
 */
@Controller
@RequestMapping("/web/goodsCate")
public class GoodsCateController extends BaseController {

    @Autowired
    private GoodsCateService goodsCateService;
    @Autowired
    private GoodImageService goodImageService;

    @RequestMapping("/toManageGoodsCate")
    public String toManageGoodsCate(){
        return "/goods/manageGoodsCate";
    }

    @ResponseBody
    @RequestMapping("/list")
    public CommonResult list(@RequestParam(required = false) String name, @RequestParam(defaultValue = "1") int pageIndex
            , @RequestParam(defaultValue = "10") int pageSize) {
        try {
            List<GoodsCate> goodsCates = goodsCateService.getGoodsCatesByPage(name,pageIndex,pageSize);
            int total = goodsCateService.getTotal(name);
            return CommonResult.createSuccessResult(goodsCates,total,"查询分类列表成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.createFailureResult("查询分类列表失败");
        }
    }

    /**
     *
     * @param id
     * @param type 1:保存 2:修改
     * @param model
     * @return
     */
    @RequestMapping("/toEditGoodsCate/{type}/{id}")
    public String toEditTeacher(@PathVariable Integer id,@PathVariable Integer type, Model model){
        if(type==2){
            if (null!=id){
                model.addAttribute("goodsCate",goodsCateService.getGoodsCateById(id));
            }
        }
        return "/goods/editGoodsCate";
    }

    @ResponseBody
    @RequestMapping("/uploadImg")
    public JsonResult uploadImg(MultipartFile file, HttpServletRequest request){
        try {
            String path = this.uploadImage(file,"goodsCate",1);
            logger.info("文件成功上传到指定目录下,文件目录:{},",path);
            GoodImage goodImage = new GoodImage();
            goodImage.setImagePath(path);
            goodImage.setCreateDatetime(new Date());
            goodImageService.saveImage(goodImage);
            return new JsonResult(goodImage.getId(),"上传成功",true);
        }catch (IOException ie){
            ie.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return new JsonResult("","上传失败",false);
    }

    @ResponseBody
    @RequestMapping("/edit")
    public JsonResult edit(GoodsCate goodsCate) {
        try {
            if (null == goodsCate.getId()) {
                goodsCate.setCreateDatetime(new Date());
                goodsCateService.save(goodsCate);
            }
            goodsCate.setpId(0);
            if (goodsCate.getpId() == 0) {
                goodsCate.setLv(1);
                goodsCate.setPath(String.valueOf(goodsCate.getId()));
            } else {
                Map<String, Object> result = getLevel(1, goodsCate.getpId(), String.valueOf(goodsCate.getpId()));
                goodsCate.setPath((String) result.get("path"));
                goodsCate.setLv((int) result.get("level"));
            }
            goodsCateService.modifyGoodsCate(goodsCate);
            return new JsonResult(null, "保存成功", true);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(null, "保存失败", false);
        }
    }

    @ResponseBody
    @RequestMapping("/getGoodImage")
    public JsonResult getGoodImage(@RequestParam(value = "id") Integer imageId){
        try {
            String path = this.getImagePath(imageId,goodImageService);
            return new JsonResult(path,"",true);
        }catch (RuntimeException e){
            e.printStackTrace();
            return new JsonResult(null,"",false);
        }
    }

    @ResponseBody
    @RequestMapping("/delete/{id}")
    public JsonResult delete(@PathVariable Integer id) {
        goodsCateService.delete(id);
        return new JsonResult(null, "删除分类成功", true);
    }

    private Map<String, Object> getLevel(int level, Integer pId, String path) {
        Map<String, Object> res = new HashMap<>();
        GoodsCate gc = goodsCateService.getGoodsCateById(pId);
        if (null != gc) {
            level++;
            path = gc.getId() + "-" + path;
        }
        if (0 != gc.getpId()) {
            return getLevel(level, gc.getpId(), path);
        }
        res.put("level", level);
        res.put("path", path);
        return res;
    }

}
